function UCWords(string) {
    var temparr = string.split(/_/g);
    var tempstr = '';
    for(key in temparr) {
        tempstr = tempstr + (temparr[key].substr(0, 1).toUpperCase() + temparr[key].substr(1).toLowerCase()) + ' ';
    }
    return tempstr;
}

function new_form(model) {
    $('#submit-form i').html('');
    $('.modal-body').html('<center><img src="/images/ajax-loader.gif" width="92" height="92" /></center>');
    $('#modal-box').modal();
    $.get(
        '/admin/'+model+'/ajaxNew',
        function(data, status) {
            $('.modal-body').html(data);
        }, 'html')
}

$(function() {
    
    $('body').append('<div id="modal-box" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="box-header" aria-hidden="true">'+
        '<div class="modal-body">'+
        '</div>'+
        '<div class="modal-footer">'+
        '<button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>'+
        '<button id="submit-form" class="btn">Guardar <i></i></button></form>'+
        '</div>'+
        '</div>');
    
    $('.sf_admin_form select').each(function() {
        var rel = $(this).attr('name').match(/\w+(?=_id)/);
        if(rel != null) {
            $(this).after('&nbsp;<button class="btn btn-mini block" onclick="new_form(\''+rel+'\'); return false;">Agregar '+UCWords(rel[0])+'</button>');
        }
    });
    
    $('#submit-form').on('click', function() {
        $(this).find('i').html('<img src="/images/ajax-loader-mini.gif" width="16" height="16" />');
        $.post(
            $('.modal-body form').attr('action'),
            $('.modal-body form').serialize(),
            function(data, status) {
                if(data.substr(0, 7) == 'SUCCESS') {
                    var id = data.match(/\[id\:([^\]]*)(?=\])/)[1]
                    var nombre = data.match(/\[nombre\:([^\]]*)(?=\])/)[1];
                    var model = data.match(/\[model\:([^\]]*)(?=\])/)[1];
                    $('[id$='+model+'_id]').append('<option value="'+id+'">'+nombre+'</option>');
                    $('[id$='+model+'_id]').val(id);
                    $('#modal-box').modal('hide');
                } else {
                    $('#submit-form i').html('');
                    $('.modal-body').html(data);
                }
            }, 'html');
    });
});